package org.feng.controller;

import cn.hutool.core.lang.tree.Tree;
import com.alibaba.excel.EasyExcel;
import org.feng.entity.CustomDict;
import org.feng.listener.CustomDictExcelListener;
import org.feng.manager.CustomDictManager;
import org.feng.vo.CustomDictExcelVo;
import org.feng.vo.CustomDictVo;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 字典控制器
 *
 * @author feng
 */
@RestController
@RequestMapping("/dict")
public class DictController {

    @Resource
    private CustomDictManager customDictManager;

    @GetMapping("/list/{id}")
    public List<Tree<Long>> listDictTree(@PathVariable("id") Long id) {
        return customDictManager.listDictTree(id);
    }

    @GetMapping("/listChildren/{id}")
    public List<CustomDictVo> listChildrenById(@PathVariable("id") Long dictId) {
        return CustomDictVo.of(customDictManager.listChildrenById(dictId));
    }


    @PostMapping("/insert")
    public String insert(@RequestBody CustomDict dict) {
        return String.valueOf(customDictManager.addDict(dict));
    }

    /**
     * 文件下载并且失败的时候返回json（默认失败了会返回一个有部分数据的Excel）
     *
     * @since 2.1.1
     */
    @GetMapping("/download")
    public void downloadFailedUsingJson(HttpServletResponse response) throws IOException {

        // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
        try {
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("字典导出", "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + System.currentTimeMillis() + ".xlsx");
            // 这里需要设置不关闭流
            EasyExcel.write(response.getOutputStream(), CustomDictExcelVo.class).autoCloseStream(Boolean.FALSE).sheet("字典")
                    .doWrite(customDictManager.customDictExcelVos());
        } catch (Exception e) {
            // 重置response
            response.reset();
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            Map<String, String> map = new HashMap<>(4);
            map.put("status", "failure");
            map.put("message", "下载文件失败" + e.getMessage());
            response.getWriter().println(map);
        }
    }

    @PostMapping("/upload")
    public String upload(@RequestParam("file") MultipartFile file) throws IOException {
        EasyExcel.read(file.getInputStream(), CustomDictExcelVo.class, new CustomDictExcelListener(customDictManager))
                .sheet()
                .doRead();

        return "success";
    }
}
